package com.hnhs.advice;

import cn.hutool.json.JSONUtil;
import com.hnhs.dto.ResponseDTO;
import com.hnhs.exception.BizException;
import com.hnhs.info.PageInfo;
import com.hnhs.threadLocal.LocalPageInfoUtil;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;

@RestControllerAdvice  //增强类 响应的结果增强
public class MyResponseAdvice implements ResponseBodyAdvice<Object> {
    //支持的方法 默认是不支持 后面的参数代表哪些数据支持 哪些数据不支持
    @Override
    public boolean supports(MethodParameter methodParameter,
                            Class<? extends HttpMessageConverter<?>> aClass) {
        //代表增强的接口
        return true;
    }

    @ExceptionHandler
    public Object processException(Exception ex){
        ex.printStackTrace();
        if(ex instanceof BizException){
            BizException bizException=(BizException)ex;
            return ResponseDTO.error(bizException.getCode(), ex.getMessage());
        }
//        ResponseDTO dto=ResponseDTO.error(88, ex.getMessage());
        return ResponseDTO.error(88, ex.getMessage());

    }

    @Override
    public Object beforeBodyWrite(Object bady,
                                  MethodParameter methodParameter,
                                  MediaType mediaType,
                                  Class<? extends HttpMessageConverter<?>> aClass,
                                  ServerHttpRequest serverHttpRequest,
                                  ServerHttpResponse serverHttpResponse) {
        if (bady instanceof ResponseDTO){
            return bady;
        }
        ResponseDTO dto=ResponseDTO.success(bady);
        PageInfo pageInfo= LocalPageInfoUtil.get();
        if(pageInfo !=null){
            HashMap<Object,Object> map=new HashMap<>();
            map.put("total",pageInfo.getTotal());
            map.put("items",bady);
            dto=ResponseDTO.success(map);
            LocalPageInfoUtil.remove();
        }

        if(aClass == StringHttpMessageConverter.class){
            //给成对应的json
            return JSONUtil.toJsonStr(dto);
        }
        return dto;
    }
}
